package com.webyweather.android;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.webyweather.android.adapter.PropositionCardsListViewAdapter;
import com.webyweather.android.constant.Constants;
import com.webyweather.android.dto.Current;
import com.webyweather.android.dto.PropositionsData;
import com.webyweather.android.loader.PropositionsDataAsyncLoader;
import com.webyweather.android.manager.ConnectionManager;

/**
 * Project webyweather
 *
 * @autor tair_mustafaiev
 * Date: 5/16/13
 * Time: 5:13 PM
 */
public class PropositionCardsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<PropositionsData>, ObservableScrollView.Callbacks {

    private Double mLongitude;

    private Double mLatitude;

    private boolean isWeatherFetched = false;

    private ImageLoader imageLoader;

    private static final int STATE_ONSCREEN = 0;

    private static final int STATE_OFFSCREEN = 1;

    private static final int STATE_RETURNING = 2;

    private RelativeLayout mQuickReturnView;

    private View mPlaceholderView;

    private ObservableScrollView mObservableScrollView;

    private int mMinRawY = 0;

    private int mState = STATE_ONSCREEN;

    private int mQuickReturnHeight;

    private int mCachedVerticalScrollRange;

    private WindowManager mWindowManager;

    private Display mDisplay;

    private LinearLayout mListWrapper;

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.proposition_cards_list, container, false);

        mObservableScrollView = (ObservableScrollView) rootView.findViewById(R.id.scroll_view);
        mQuickReturnView = (RelativeLayout) rootView.findViewById(R.id.weather_container);
        mObservableScrollView.setCallbacks(this);
        mPlaceholderView = rootView.findViewById(R.id.placeholder);

        mWindowManager = (WindowManager) getSherlockActivity().getSystemService(Context.WINDOW_SERVICE);
        mDisplay = mWindowManager.getDefaultDisplay();
        mListWrapper = (LinearLayout) rootView.findViewById(R.id.list_wraper);

        mObservableScrollView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout () {
                        onScrollChanged();
                        mCachedVerticalScrollRange = mObservableScrollView.computeVerticalScrollRange();
                        mQuickReturnHeight = mQuickReturnView.getHeight();
                        //resizeWindow();
                    }
                });

        return rootView;
    }

    @Override
    public void onResume () {
        super.onResume();
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ConnectionManager connectionManager = new ConnectionManager();
        if (connectionManager.isNetworkConnected(getSherlockActivity())) {
            this.getView().findViewById(R.id.weather_container).setVisibility(View.INVISIBLE);
            Intent i = getSherlockActivity().getIntent();
            mLongitude = (Double) i.getBundleExtra(Constants.LONGLAT).get(Constants.LONGITUDE);
            mLatitude = (Double) i.getBundleExtra(Constants.LONGLAT).get(Constants.LATITUDE);

            if (!isWeatherFetched) {
                getLoaderManager().initLoader(11, null, PropositionCardsFragment.this);
            }

            this.imageLoader = ImageLoader.getInstance();
            PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, true, true);
            getListView().setOnScrollListener(listener);

        } else {
            Toast.makeText(getSherlockActivity(), getText(R.string.no_connection), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public Loader<PropositionsData> onCreateLoader (int i, Bundle bundle) {
        return new PropositionsDataAsyncLoader(this.getSherlockActivity(), mLatitude, mLongitude);
    }

    @Override
    public void onLoadFinished (Loader<PropositionsData> propositionsDataLoader, PropositionsData fragmentData) {
        if (fragmentData != null) {
            Current current = fragmentData.getWeather().getCurrent();
            isWeatherFetched = true;
            if (current != null) {
                Activity activity = this.getSherlockActivity();
                TextView city = (TextView) activity.findViewById(R.id.weather_city);
                city.setText(fragmentData.getAddress().get(0).getLong_name() + ", " + fragmentData.getAddress().get(1).getLong_name());

                TextView date = (TextView) activity.findViewById(R.id.weather_date);
                date.setText(current.getObservationTime());

                TextView desc = (TextView) activity.findViewById(R.id.weather_desc);
                desc.setText(current.getWeatherDesc().get(0).getValue());

                TextView temp = (TextView) activity.findViewById(R.id.weather_temperature);
                temp.setText(current.getTemp_C());

                ImageView wi = (ImageView) activity.findViewById(R.id.weather_image);

                imageLoader.displayImage(current.getWeatherIconUrl().get(0).getValue(), wi, new DisplayImageOptions.Builder()
                        .showImageForEmptyUri(R.drawable.no_image)
                        .showImageOnFail(R.drawable.no_image)
                        .cacheInMemory(true)
                        .cacheOnDisc(true)
                        .build());

                setListAdapter(new PropositionCardsListViewAdapter(getSherlockActivity(), fragmentData.getPropositions(), imageLoader));
                //resizeWindow();
                this.getView().findViewById(R.id.weather_container).setVisibility(View.VISIBLE);
            } else {
                Toast.makeText(getSherlockActivity(), getText(R.string.error_message), Toast.LENGTH_LONG).show();
            }

        } else {
            Toast.makeText(getSherlockActivity(), getText(R.string.error_message), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onLoaderReset (Loader<PropositionsData> weatherDataLoader) {
    }


    private void resizeWindow () {

        int childCount = getListView().getChildCount();
        int totalHeight = 0;
        for (int i = 0; i < childCount; i++) {
            totalHeight = totalHeight + getListView().getDividerHeight() + getListView().getChildAt(i).getHeight();
        }

        if (mListWrapper != null && totalHeight == 0) {
            Point size = new Point();
            try {
                mDisplay.getSize(size);
                totalHeight = size.y;
            } catch (NoSuchMethodError e) {
                totalHeight = mDisplay.getHeight();
            }
        }

//        mListWrapper.setMinimumHeight(totalHeight + 1000);
        mListWrapper.invalidate();
        mListWrapper.getLayoutParams().height = totalHeight;
        mListWrapper.requestLayout();
    }

    @Override
    public void onScrollChanged () {
        int rawY = mPlaceholderView.getTop() - Math.min(
                mCachedVerticalScrollRange - mObservableScrollView.getHeight(),
                mObservableScrollView.getScrollY());
        int translationY = 0;

        switch (mState) {
            case STATE_OFFSCREEN:
                resizeWindow();
                if (rawY <= mMinRawY) {
                    mMinRawY = rawY;
                } else {
                    mState = STATE_RETURNING;
                }
                translationY = rawY;
                break;

            case STATE_ONSCREEN:
                resizeWindow();
                if (rawY < -mQuickReturnHeight) {
                    mState = STATE_OFFSCREEN;
                    mMinRawY = rawY;
                }
                translationY = rawY;
                break;

            case STATE_RETURNING:
                resizeWindow();
                translationY = (rawY - mMinRawY) - mQuickReturnHeight;
                if (translationY > 0) {
                    translationY = 0;
                    mMinRawY = rawY - mQuickReturnHeight;
                }

                if (rawY > 0) {
                    mState = STATE_ONSCREEN;
                    translationY = rawY;
                }

                if (translationY < -mQuickReturnHeight) {
                    mState = STATE_OFFSCREEN;
                    mMinRawY = rawY;
                }
                break;
        }

        mQuickReturnView.setTranslationY(translationY);
    }
}
